<template>
  <div>
    <!-- 项目头部信息 -->
    <div style="margin-bottom: 20px; padding: 20px; background: #fff; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1)">
      <div style="display: flex; justify-content: space-between; align-items: flex-start">
        <div style="flex: 1">
          <div style="display: flex; align-items: center; margin-bottom: 10px">
            <el-button link @click="$router.go(-1)" style="padding: 0; margin-right: 10px">
              <el-icon><ArrowLeft /></el-icon>
            </el-button>
            <h2 style="margin: 0; color: #333">{{ projectInfo.projectName }}</h2>
            <el-tag :type="getStatusTagType(projectInfo.projectStatus)" style="margin-left: 10px">
              {{ getStatusText(projectInfo.projectStatus) }}
            </el-tag>
          </div>
          <p style="margin: 0; color: #666; font-size: 14px">{{ projectInfo.projectDescription }}</p>
          <div style="margin-top: 10px; display: flex; align-items: center; gap: 20px">
            <div style="display: flex; align-items: center">
              <span style="color: #999; margin-right: 5px">项目标识:</span>
              <span style="font-weight: 500">{{ projectInfo.projectKey || projectInfo.projectId }}</span>
            </div>
            <div style="display: flex; align-items: center">
              <span style="color: #999; margin-right: 5px">负责人:</span>
              <el-avatar :size="20" src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png" style="margin-right: 5px" />
              <span>{{ projectInfo.projectLeader }}</span>
            </div>
            <div style="display: flex; align-items: center">
              <span style="color: #999; margin-right: 5px">成员:</span>
              <span>{{ projectInfo.memberCount }} 人</span>
            </div>
          </div>
        </div>
        <div style="display: flex; gap: 10px">
          <el-button @click="showSettingsDialog = true">
            <el-icon><Setting /></el-icon>
            项目设置
          </el-button>

        </div>
      </div>
    </div>

    <!-- 项目导航 -->
    <div style="margin-bottom: 20px">
      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <!-- Overview tab removed -->
        <el-tab-pane label="工作项" name="tasks">
          <ProjectTasks :project-id="projectId" />
        </el-tab-pane>
        <el-tab-pane label="成员" name="members">
          <ProjectMembers :project-id="projectId" />
        </el-tab-pane>
      </el-tabs>
    </div>



    <!-- 项目设置对话框 -->
    <el-dialog v-model="showSettingsDialog" title="项目设置" width="600px">
      <el-form :model="projectInfo" label-width="100px">
        <el-form-item label="项目名称">
          <el-input v-model="projectInfo.projectName" />
        </el-form-item>
        <el-form-item label="项目描述">
          <el-input v-model="projectInfo.projectDescription" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="项目状态">
          <el-select v-model="projectInfo.projectStatus">
            <el-option label="进行中" value="active" />
            <el-option label="已完成" value="completed" />
            <el-option label="已暂停" value="paused" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="项目负责人">
          <el-input v-model="projectInfo.projectLeader" disabled />
          <div style="color: #909399; font-size: 12px; margin-top: 5px;">
            项目负责人不可修改
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showSettingsDialog = false">取消</el-button>
        <el-button type="primary" @click="saveProjectSettings">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'
// ProjectOverview component removed
import ProjectTasks from './project/ProjectTasks.vue'
import ProjectMembers from './project/ProjectMembers.vue'

const route = useRoute()
const projectId = computed(() => route.params.id)

// 响应式数据
const activeTab = ref('tasks')

const showSettingsDialog = ref(false)


// 项目信息
const projectInfo = reactive({
  projectId: null,
  projectName: '',
  projectKey: '',
  projectDescription: '',
  projectStatus: '',
  projectPriority: '',
  projectLeader: '',
  memberCount: 0,
  progress: 0,
  startTime: '',
  endTime: ''
})





// 加载项目信息
const loadProjectInfo = async () => {
  if (!projectId.value) {
    ElMessage.error('项目ID不能为空')
    return
  }

  try {
    const response = await request.get(`/api/kanban/projects/${projectId.value}`)
    if (response.code === '200' && response.data) {
      Object.assign(projectInfo, response.data)
    } else {
      ElMessage.error(response.msg || '获取项目信息失败')
    }
  } catch (error) {
    // 记录错误信息到控制台（非错误级别）
    console.info({
      message: '获取项目信息错误',
      error: error.message,
      timestamp: new Date().toISOString(),
      type: 'project_info_error'
    });

    // 处理不同类型的错误
    if (error.response) {
      // 服务器响应错误
      const status = error.response.status;
      const data = error.response.data;
      
      switch (status) {
        case 400:
          ElMessage.error(data.msg || '请求参数错误');
          break;
        case 401:
          ElMessage.error('身份验证失败，请重新登录');
          break;
        case 403:
          ElMessage.error('权限不足，无法查看项目信息');
          break;
        case 404:
          ElMessage.error('项目不存在或已被删除');
          break;
        case 500:
          ElMessage.error('服务器内部错误，请稍后重试');
          break;
        case 503:
          ElMessage.error('服务暂时不可用，请稍后重试');
          break;
        default:
          ElMessage.error(data.msg || `获取项目信息失败 (错误代码: ${status})`);
      }
    } else if (error.request) {
      // 网络错误
      if (error.code === 'ECONNABORTED') {
        ElMessage.error('请求超时，请检查网络连接后重试');
      } else if (error.message.includes('Network Error')) {
        ElMessage.error('网络连接失败，请检查网络设置');
      } else {
        ElMessage.error('网络请求失败，请稍后重试');
      }
    } else {
      // 其他错误
      ElMessage.error('获取项目信息时发生未知错误，请稍后重试');
    }
  }
}

// 方法
const handleTabChange = (tabName) => {
  // 可以在这里处理标签页切换逻辑
  console.log('切换到标签页:', tabName)
}

const saveProjectSettings = async () => {
  try {
    // 获取当前登录用户
    const systemUser = JSON.parse(localStorage.getItem('system-user') || '{}');
    const currentUser = systemUser.username || localStorage.getItem('username');
    
    // 检查当前用户是否是项目负责人
    if (projectInfo.projectLeader !== currentUser) {
      ElMessage.warning('只有项目负责人才能修改项目设置');
      return;
    }
    
    // 发送更新请求
    const response = await request.put(`/api/kanban/projects/${projectInfo.projectId}`, {
      projectName: projectInfo.projectName,
      projectDescription: projectInfo.projectDescription,
      projectStatus: projectInfo.projectStatus,
      // 不包含projectLeader字段，确保不会修改项目负责人
    });
    
    if (response.code === '200') {
      ElMessage.success('项目设置已保存');
      showSettingsDialog.value = false;
      // 重新加载项目信息
      loadProjectInfo();
    } else {
      ElMessage.error(response.msg || '保存项目设置失败');
    }
  } catch (error) {
    // 记录错误信息到控制台（非错误级别）
    console.info({
      message: '保存项目设置错误',
      error: error.message,
      timestamp: new Date().toISOString(),
      type: 'project_settings_save_error'
    });

    // 处理不同类型的错误
    if (error.response) {
      // 服务器响应错误
      const status = error.response.status;
      const data = error.response.data;
      
      switch (status) {
        case 400:
          ElMessage.error(data.msg || '请求参数错误，请检查项目信息');
          break;
        case 401:
          ElMessage.error('身份验证失败，请重新登录');
          break;
        case 403:
          ElMessage.error('权限不足，无法修改项目设置');
          break;
        case 404:
          ElMessage.error('项目不存在或已被删除');
          break;
        case 409:
          ElMessage.error('项目名称已存在，请选择其他名称');
          break;
        case 422:
          ElMessage.error(data.msg || '数据验证失败');
          break;
        case 500:
          ElMessage.error('服务器内部错误，请稍后重试');
          break;
        case 503:
          ElMessage.error('服务暂时不可用，请稍后重试');
          break;
        default:
          ElMessage.error(data.msg || `保存项目设置失败 (错误代码: ${status})`);
      }
    } else if (error.request) {
      // 网络错误
      if (error.code === 'ECONNABORTED') {
        ElMessage.error('请求超时，请检查网络连接后重试');
      } else if (error.message.includes('Network Error')) {
        ElMessage.error('网络连接失败，请检查网络设置');
      } else {
        ElMessage.error('网络请求失败，请稍后重试');
      }
    } else {
      // 其他错误
      ElMessage.error('保存项目设置时发生未知错误，请稍后重试');
    }
  }
}

// 工具方法
const getStatusTagType = (status) => {
  const types = {
    active: 'success',
    completed: 'info',
    paused: 'warning',
    cancelled: 'danger'
  }
  return types[status] || ''
}

const getStatusText = (status) => {
  const texts = {
    active: '进行中',
    completed: '已完成',
    paused: '已暂停',
    cancelled: '已取消'
  }
  return texts[status] || status
}

// 生命周期
onMounted(() => {
  // 根据路由参数加载项目信息
  console.log('加载项目:', projectId.value)
  loadProjectInfo()
})
</script>

<style scoped>
:deep(.el-tabs__header) {
  margin-bottom: 0;
}

:deep(.el-tabs__content) {
  padding: 0;
}

:deep(.el-tab-pane) {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  min-height: 400px;
}
</style>